package com.AAL.DAO;

import java.sql.Timestamp;
import java.util.List;

import org.hibernate.classic.Session;

import com.AAL.DAO.Interface.IPaymentOfDealerDAO;
import com.AAL.Model.Dealer;
import com.AAL.Model.PaymentOfDealer;
import com.AAL.Utils.HibernateUtil;

public class PaymentOfDealerDAO implements IPaymentOfDealerDAO {

	@Override
	public PaymentOfDealer saveAndUpdatePaymentOfDealer(PaymentOfDealer payment) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		try {
			session.saveOrUpdate(payment);
		} catch (Exception e) {
			return null;
		}
		session.getTransaction().commit();
		return payment;
	}

	@Override
	public PaymentOfDealer deletePaymentOfDealer(int paymentID) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		try {
			session.beginTransaction();
			PaymentOfDealer payment = (PaymentOfDealer) session.load(
					PaymentOfDealer.class, paymentID);
			if (null != payment) {
				session.delete(payment);
			}
			session.getTransaction().commit();
			return payment;
		} catch (Exception e) {
			e.printStackTrace();
			session.getTransaction().rollback();
			return null;
		}
	}

	@Override
	public PaymentOfDealer getPaymentOfDealer(int paymentID) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		PaymentOfDealer payment = (PaymentOfDealer) session.load(
				PaymentOfDealer.class, paymentID);
		return payment;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<PaymentOfDealer> getLstPaymentOfDealerByDealer(Dealer dealer,
			Timestamp fromDate, Timestamp toDate) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List<PaymentOfDealer> lstPaymentOfDealers = null;
		try {
			lstPaymentOfDealers = session
					.createQuery(
							"from PaymentOfDealer where dealer.dealerID=:dealerID and paymentDate between :begin and :end")
					.setParameter("dealerID", dealer.getDealerID())
					.setParameter("begin", fromDate)
					.setParameter("end", toDate).list();
		} catch (Exception e) {
			return null;
		}
		session.getTransaction().commit();
		return lstPaymentOfDealers;
	}

	@SuppressWarnings("unchecked")
	public List<PaymentOfDealer> getAllLstPaymentOfDealersByDealer(Dealer dealer) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List<PaymentOfDealer> lstPaymentOfDealers = null;
		try {
			lstPaymentOfDealers = session
					.createQuery(
							"from PaymentOfDealer where dealer.dealerID=:dealerID")
					.setParameter("dealerID", dealer.getDealerID()).list();
		} catch (Exception e) {
			return null;
		}
		session.getTransaction().commit();
		return lstPaymentOfDealers;
	}
}
